const fs = require('fs');
const axios = require('axios');
const path = require('path');
const cheerio = require('cheerio');
const { downloadImage } = require('./download');
const { minify } = require('html-minifier');
const beautify = require('js-beautify').html;
const html2pug = require('html2pug');
const { imageSizeFromFile } = require('image-size/fromFile')


/*
 * 读取 HTML 文件
 */
async function extractProject(htmlContent, params) {
  const { name, url, folder } = params;
  const caseFolder = path.join(__dirname, `../../${folder}`, name);

  // 压缩 HTML 文档
  const minifiedHtml = minify(htmlContent, {
    removeAttributeQuotes: true,
    collapseWhitespace: true,
    minifyCSS: true,
    minifyJS: true,
    removeComments: true,
  });

  // 使用 cheerio 加载 HTML 内容
  const $ = cheerio.load(minifiedHtml);
  // 提取 id 为 page-content 的 div
  // const pageContentDiv = $('#page-content');
  const pageContentDiv = $('#activity-detail');

  // 创建新的 HTML 内容，仅包含 body 和提取的 div
  const newHtmlContent = `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Modified HTML</title>
</head>
<body>
    ${pageContentDiv.html()}
</body>
</html>
`;

  // 格式化 HTML 文档
  const formattedHtml = beautify(newHtmlContent, {
    indent_size: 2,
    space_in_empty_paren: true,
  });

  const { updatedHtml } = processDom(formattedHtml, params);


  // 保存修改后的 HTML 到新文件
  fs.writeFileSync(`${caseFolder}/index.html`, updatedHtml, 'utf8');
  // 保存原始网址
  fs.writeFileSync(`${caseFolder}/url.txt`, url, 'utf8');

  // 修改pug文件
  const html = cheerio.load(updatedHtml);
  const svgSection = html('body');
  const pugContent = html2pug(`${svgSection.html() || '<h1> 内容未找到<h1>'}`);
  // fs.writeFileSync(`${caseFolder}/home.pug`, replaceQuotation(pugContent), 'utf8');

  // 提取PUG中的 URL 并逐个替换
  let urlIndex = 0; // 用于跟踪新 URL 的索引

  // 创建images目录
  const imagesDir = path.join(caseFolder, 'images');
  fs.mkdir(imagesDir, { recursive: true }, (err) => {
    if (err) { return console.error(`创建目录时出错: ${err.message}`); }
  });

  const allUrls = []

  // 去掉重复的url版本, 有bug
  const urlMap = new Map();
  const updatedPug = pugContent.replace(/url\("([^"]+)"\)|data-src='([^']+)'|data-src="([^"]+)"/g, (match, bgUrl, imgUrl, imgUrl2) => {
    const currentUrl = bgUrl || imgUrl || imgUrl2;

    if (urlMap.has(currentUrl)) {
      return urlMap.get(currentUrl); // 返回缓存的替换结果
    }

    let replacement;
    if (bgUrl) {
      replacement = `url("\${images[${urlIndex}].url}")`;
    } else {
      replacement = `data-src=\`\${images[${urlIndex}].url}\``;
    }

    allUrls.push(currentUrl);
    urlMap.set(currentUrl, replacement);
    urlIndex++;

    return replacement;
  });

  /*
const updatedPug = pugContent.replace(/url\("([^"]+)"\)|data-src='([^']+)'|background-image:url\("([^"]+)"\)/g, (match, bgUrl, imgUrl, svgBgUrl) => {
  if (bgUrl) {
    allUrls.push(bgUrl);
    return `url("\${images[${urlIndex++}].url}")`; // 替换 background-image URL
  } else if (imgUrl) {
    allUrls.push(imgUrl);
    return `data-src="\${images[${urlIndex++}].url}"`; // 替换 img src URL
  } else if (svgBgUrl) {
    allUrls.push(svgBgUrl);
    return `background-image:url("\${images[${urlIndex++}].url}")`; // 替换 SVG background-image URL
  }
  return match;
});
*/

  // 保存修改后的PUG 到新文件
  const headerPug = ['extends ../../src/pug/index.pug', 'block body']
  const cleanPugContent = formatPug(updatedPug, 6, 11, headerPug);

  fs.writeFileSync(`${caseFolder}/home.pug`, replaceQuotation(cleanPugContent), 'utf8');

  // 写入图片文件,并生成urls.json内容
  const urlsJson = []
  for (let index = 0; index < allUrls.length; index++) {
    const url = allUrls[index]
    const imgName = await downloadImage(url, imagesDir, `${name}-${index}`)
    const { width, height } = await imageSizeFromFile(path.join(imagesDir, imgName));
    urlsJson.push({ index, file: imgName, url, width, height })
  };

  // 写入urls.json文件
  fs.writeFileSync(
    path.join(caseFolder, 'urls.json'),
    JSON.stringify(urlsJson, null, 2)
  );

  console.log(`\n✅${name} 下载成! 请访问: http://localhost:3333/${name}\n`);
}

/*
  * 将 style 属性值中的单引号替换为反引号
  */
function replaceQuotation(htmlString) {
  return htmlString.replace(/'/g, '`')
  // .replace(/(https?:\/\/)/g, '/proxy?url=$1');// 增加图片代理
}

/*
  * 处理DOM
  */
function processDom(htmlContent, params) {
  const { name } = params
  const caseFolder = path.join(__dirname, '../../../samples', name);
  const caseName = caseFolder.split('/')[caseFolder.split('/').length - 1]
  const $ = cheerio.load(htmlContent);

  const REMAINING_DOM_IDS = ['content_bottom_area', 'activity-name', 'meta_content']
  const REMAINING_ATTRS = [
    'class', 'data-fill', 'data-cpy', 'data-copyright', 'name', 'id', 'data-fail', 'data-mpa-powered-by',
    'data-lazy-bgimg', 'powered-by', 'data-wechat', 'label', 'copyright', 'data-mpa-powered-by'
  ]

  REMAINING_DOM_IDS.forEach(domId => {
    $(`#${domId}`).remove(); // 删除多余dom
  })

  const IMAGE_FOLDER = 'images'
  const imgFolder = `${caseFolder}/${IMAGE_FOLDER}`
  // 遍历所有元素
  $('*').each((i, element) => {

    // 删除多余属性
    REMAINING_ATTRS.forEach(attr => { $(element).removeAttr(attr); })

    Object.keys($(element).data()).forEach(attr => {
      // 删除以 data-v- 开头的属性
      if (attr.startsWith('v-')) {
        $(element).removeAttr(`data-${attr}`);
      }
    });

    /*
    // 检查是否同时存在 data-src 和 src 属性
    if ($(element).tagName === 'img') {
      const dataSrc = $(element).attr('data-src');
      if (dataSrc) { $(element).attr('src', dataSrc); }
    }
    */

    // 删除所有属性值为空的属性
    Object.keys($(element).attr()).forEach(attr => {
      const attrValue = $(element).attr(attr);
      if (attrValue === '' || attrValue === 'undefined' || attrValue === 'null') {
        $(element).removeAttr(attr);
      }
    });

    // 处理内联样式
    const style = $(element).attr('style'); // 获取内联样式
    if (style) {
      const urlRegex = /url\(['"]?([^'")]+)['"]?\)/g; // 匹配 url()
      let match;

      // 查找所有 url()
    }

  });

  return { updatedHtml: $.html() };
}

module.exports = {
  extractProject,
};

function formatPug(text, linesToRemoveFromStart, linesToRemoveFromEnd, newLines) {
  // 将文本按行分割成数组
  const lines = text.split('\n');

  // 删除前6行
  const updatedLines = lines.slice(linesToRemoveFromStart);

  // 删除尾部的11行
  const finalLines = updatedLines.slice(0, updatedLines.length - linesToRemoveFromEnd);

  // 在前面添加新行
  return [...newLines, ...finalLines].join('\n');
}
